$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'stockInfo/list',
        datatype: "json",
        colModel: [
            {label: '股票代码', name: 'stockCode', index: 'stock_code', width: 80, classes: 'code-style'},
            {label: '简称', name: 'stockName', index: 'stock_name', width: 80},
            {
                label: '当前价', name: 'currentPrice', index: 'current_price', width: 80,
                formatter: function (value, options, row) {
                    return row.priceLimit < 0 ?
                        '<span style="color:#0ebe98;font-size:15px;">' + row.currentPrice + '<i style="margin-left:3px" class="fa fa-long-arrow-down" aria-hidden="true"></i></span>' :
                        '<span style="color:red;font-size:15px;">' + row.currentPrice + '<i style="margin-left:3px" class="fa fa-long-arrow-up" aria-hidden="true"></i></span>';
                }
            },
            {
                label: '涨跌幅', name: 'priceLimit', index: 'price_limit', width: 80,
                formatter: function (value, options, row) {
                    return row.priceLimit < 0 ?
                        '<span style="color:#0ebe98;font-size:15px;">' + (row.priceLimit * 100).toFixed(2) + '%</span>' :
                        '<span style="color:red;font-size:15px;">+' + (row.priceLimit * 100).toFixed(2) + '%</span>';
                }
            },
            {label: '板块', name: 'industry', index: 'listing_date', width: 80},
            {label: '上市日期', name: 'listingDate', index: 'listing_date', width: 80},
            {label: '类型', name: 'stockType', index: 'stock_type', width: 80},
            {label: '总股本', name: 'marketCapital', index: 'market_capital', width: 80},
            {label: '流通股', name: 'negotiableCapital', index: 'negotiable_capital', width: 80},
            {label: '证券交易所', name: 'stockExchange', index: 'stock_exchange', width: 80},
            {label: '公司网址', name: 'website', index: 'website', width: 80}
        ],
        viewrecords: true,
        height: 450,
        rowNum: 10,
        rowList: [10, 30, 50, 100, 200, 300],
        rownumbers: true,
        rownumWidth: 60,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        },
        onCellSelect: function (rowid, iCol, cellcontent, e) {
            if (iCol == 1) {
                vm.showList = false;
                $.getJSON(baseURL + '/stockDay/getStockKLine?stockCode=' + cellcontent, function (result) {
                    if (result.data.length < 1) return;
                    renderKChart(result.stockName, result.title, result.data);
                });
            }
        }
    });

    /*上传上交所股票*/
    new AjaxUpload('#importSHStock', {
        action: baseURL + "stockInfo/importFile?stockExchange=sh",
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {
            if (!(extension && /^(xlsx||xls)$/.test(extension.toLowerCase()))) {
                alert('只支持xlsx、xls格式的文件！');
                return false;
            }
        },
        onComplete: function (file, r) {
            if (r.code == 0) {
                alert("成功导入股票信息!");
                vm.reload();
            } else {
                alert(r.msg);
            }
        }
    });

    /*上传深交所股票*/
    new AjaxUpload('#importSZStock', {
        action: baseURL + "stockInfo/importFile?stockExchange=sz",
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {
            if (!(extension && /^(xlsx||xls)$/.test(extension.toLowerCase()))) {
                alert('只支持xlsx、xls格式的文件！');
                return false;
            }
        },
        onComplete: function (file, r) {
            if (r.code == 0) {
                alert("成功导入股票信息!");
                vm.reload();
            } else {
                alert(r.msg);
            }
        }
    });

});

var vm = new Vue({
    el: '#rrapp',
    data: {
        industryOptions: [],
        items: [
            {type: '', label: '银行', color: '#409EFF'},
            {type: 'success', label: '证券', color: '#67C23A'},
            {type: 'Warning', label: '航空', color: '#E6A23C'},
            {type: 'danger', label: '地产', color: '#F56C6C'},
            {type: 'info', label: '机电', color: '#909399'},
            {type: '', label: '钢', color: '#909399'},
            {type: '', label: '电力'},
            {type: '', label: '工'},
            {type: '', label: '农'},
            {type: '', label: '生物'},
            {type: '', label: '药'},
            {type: '', label: '传媒'},
            {type: '', label: '能源'}
        ],
        suggestSearch: [],
        q: {
            stockName: '',
            stockCode: '',
            industry: '',
            type: 1
        },
        showList: true,
        title: null,
        stockInfo: {}
    },
    methods: {
        showInput: function (tag) {
            vm.q.stockName = tag.currentTarget.innerText;
        },
        getHistoryPrice: function () {
            vm.showList = false;
            clearTopDiv();
            vm.getHistoryPriceLoad = true;
            var ids = $('#jqGrid').jqGrid('getDataIDs');
            for (let n in ids) {
                $.getJSON(baseURL + '/stockDay/getStockKLine?stockCode=' + $('#jqGrid').jqGrid('getRowData', ids[n]).stockCode, function (result) {
                    if (result.data.length < 1) return;
                    renderKChart(result.stockName, result.title, result.data);
                });
            }
            vm.getHistoryPriceLoad = false;
        },
        querySearch(queryString, cb) {
            var s = vm.suggestSearch;
            var results = queryString ? s.filter(vm.createFilter(queryString)) : s;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (item) => {
                return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
            };
        },
        handleSelect(item) {
            console.log(item);
        },
        query: function () {
            console.log("query")
            vm.reload();
        },
        del: function () {
            $.ajax({
                type: "GET",
                url: baseURL + "stockInfo/deleteAllStock",
                contentType: "application/json",
                success: function (r) {
                    if (r.code == 0) {
                        alert('操作成功', function (index) {
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        reload: function (event) {
            console.log("开始查询");
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            console.log("当前页:" + page);
            console.log("查询参数:" + JSON.stringify(vm.q));
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'stockName': vm.q.stockName,
                    'industry': vm.q.industry,
                    'type': vm.q.type,
                    'stockCode': vm.q.stockCode
                },
                page: page
            }).trigger("reloadGrid");
        },
        back: function (event) {
            vm.showList = true;
            clearTopDiv();
        },
        loadAll: function () {
            /*页面展示列表显示字段默认是value，可以通过value-key="address"修改*/
            return [
                {"value": "银行"},
                {"value": "证券"},
                {"value": "钢"},
                {"value": "电力"},
                {"value": "机电"},
                {"value": "工"},
                {"value": "农"},
                {"value": "药"},
                {"value": "能源"},
                {"value": "地产"},
                {"value": "航空"}
            ]
        }
    },
    mounted() {
        this.suggestSearch = this.loadAll();
    }
});

$.ajax({
    type: "GET",
    url: baseURL + "stockInfo/industry",
    contentType: "application/json",
    success: function (result) {
        console.log(result.list);
        vm.industryOptions = result.list;
    }
});
